<?php 
/*
* StiPHPcms, A web Content management System made with PHP/MySQL
* JordSti : jord52@gmail.com
* Version : 0.0.2
*
* Copyright (C) 2009  jord52@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

class cfgStream
{
	public $entry;
	public $count;
	public $path;
	private $mode;
	
	public function __construct($path,$mode = 'default')
	{
		$this->mode = $mode;
		$this->path = $path;
		$this->count = 0;
		$this->entry = array();
		
		if(!file_exists($path))
		{
			$fp = fopen($path,'w');
			fclose($fp);
			chmod($path,0777);
		}
		
		$fp = fopen($path,'r');
		
		$file = '';
		while($line = fgets($fp))
		{
			$file .= $line;
		}
		fclose($fp);
		
		$this->parseVariable($file);
		
	}
	
	private function parseVariable($file)
	{
		if($this->mode == 'default')
		{
			preg_match_all('#(.+)=(.+);\n#isU',$file,$matches);
		}
		else if($this->mode == 'string')
		{
			preg_match_all('#(.+)=\#str\#(.+);\n#isU',$file,$matches);
		}
		else if($this->mode == 'int')
		{
			preg_match_all('#(.+)=\#int\#(.+);\n#isU',$file,$matches);
		}
		
		$count = count($matches[0]);
		$this->count = $count;
		
		for($i=0;$i<$count;$i++)
		{
			$key = $matches[1][$i];
			$this->entry[$key] = addslashes($matches[2][$i]);
		}
	}
	
	public function addVariable($name,$value)
	{
		$this->entry[$name] = $value;
	}
	
	public function isVariableExist($name)
	{
		return array_key_exists($name,$this->entry);
	}
	
	public function save()
	{
		$fp = fopen($this->path,'w');
		
		foreach($this->entry as $key => $value)
		{
			if($this->mode =='default')
			{
				fwrite($fp,$key."=".$value.";\n");
			}
			if($this->mode =='string')
			{
				fwrite($fp,$key."=#str#".$value.";\n");
			}
			else if($this->mode == 'int')
			{
				fwrite($fp,$key."=#int#".$value.";\n");
			}
		}
		
		fclose($fp);
	}
}
?>